<template>
  <div class="game-over-overlay">
    <div class="game-over-screen" :class="{ 'victory': isVictory }">
      <!-- 游戏结果标题 -->
      <div class="result-header">
        <div class="result-icon" :class="{ 'victory': isVictory }">
          <i :class="isVictory ? 'icon-trophy' : 'icon-skull'"></i>
        </div>
        <h2 class="result-title">
          {{ isVictory ? '恭喜通关！' : '游戏结束' }}
        </h2>
        <p class="result-subtitle">
          {{ isVictory ? '你成功完成了所有挑战！' : '再接再厉，下次一定能做得更好！' }}
        </p>
      </div>

      <!-- 游戏统计 -->
      <div class="game-statistics">
        <div class="stats-grid">
          <div class="stat-card primary">
            <div class="stat-icon">
              <i class="icon-star"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ formattedFinalScore }}</div>
              <div class="stat-label">最终分数</div>
              <div v-if="isNewHighScore" class="stat-badge">新纪录!</div>
            </div>
          </div>

          <div class="stat-card secondary">
            <div class="stat-icon">
              <i class="icon-distance"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ formattedDistance }}m</div>
              <div class="stat-label">跑步距离</div>
              <div v-if="isNewDistanceRecord" class="stat-badge">新纪录!</div>
            </div>
          </div>

          <div class="stat-card accent">
            <div class="stat-icon">
              <i class="icon-time"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ formattedPlayTime }}</div>
              <div class="stat-label">游戏时间</div>
            </div>
          </div>

          <div class="stat-card success">
            <div class="stat-icon">
              <i class="icon-coin"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ coinsCollected }}</div>
              <div class="stat-label">收集金币</div>
            </div>
          </div>
        </div>

        <!-- 详细统计 -->
        <div class="detailed-stats">
          <div class="stats-section">
            <h4>游戏表现</h4>
            <div class="stats-list">
              <div class="stats-item">
                <span class="stats-name">跳跃次数</span>
                <span class="stats-value">{{ jumpCount }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-name">滑铲次数</span>
                <span class="stats-value">{{ slideCount }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-name">道具收集</span>
                <span class="stats-value">{{ powerUpsCollected }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-name">完美跳跃</span>
                <span class="stats-value">{{ perfectJumps }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-name">连击次数</span>
                <span class="stats-value">{{ maxCombo }}</span>
              </div>
            </div>
          </div>

          <div class="stats-section">
            <h4>角色信息</h4>
            <div class="character-info">
              <div class="character-avatar">
                <img :src="characterAvatar" :alt="characterName">
              </div>
              <div class="character-details">
                <div class="character-name">{{ characterName }}</div>
                <div class="character-level">等级 {{ characterLevel }}</div>
                <div class="experience-bar">
                  <div class="exp-fill" :style="{ width: experiencePercentage + '%' }"></div>
                </div>
                <div class="exp-text">{{ currentExp }}/{{ nextLevelExp }} EXP</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 成就展示 -->
      <div v-if="newAchievements.length > 0" class="achievements-section">
        <h3>新成就解锁！</h3>
        <div class="achievements-list">
          <div 
            v-for="achievement in newAchievements"
            :key="achievement.id"
            class="achievement-item"
            :class="achievement.rarity"
          >
            <div class="achievement-icon">
              <i :class="achievement.icon"></i>
            </div>
            <div class="achievement-info">
              <div class="achievement-name">{{ achievement.name }}</div>
              <div class="achievement-description">{{ achievement.description }}</div>
              <div class="achievement-reward">+{{ achievement.reward }} 金币</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 排行榜预览 -->
      <div v-if="showLeaderboard" class="leaderboard-preview">
        <h3>排行榜</h3>
        <div class="leaderboard-list">
          <div 
            v-for="(record, index) in topScores"
            :key="index"
            class="leaderboard-item"
            :class="{ 'current': record.isCurrent }"
          >
            <div class="rank">{{ index + 1 }}</div>
            <div class="score">{{ record.score.toLocaleString() }}</div>
            <div class="distance">{{ record.distance }}m</div>
            <div class="date">{{ formatDate(record.date) }}</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button 
          class="action-btn primary large"
          @click="playAgain"
          :disabled="isLoading"
        >
          <i class="icon-restart"></i>
          <span>再玩一次</span>
        </button>

        <div class="secondary-buttons">
          <button 
            class="action-btn secondary"
            @click="shareScore"
            :disabled="isLoading"
          >
            <i class="icon-share"></i>
            <span>分享成绩</span>
          </button>

          <button 
            class="action-btn secondary"
            @click="viewStats"
            :disabled="isLoading"
          >
            <i class="icon-chart"></i>
            <span>查看统计</span>
          </button>

          <button 
            class="action-btn secondary"
            @click="changeCharacter"
            :disabled="isLoading"
          >
            <i class="icon-character"></i>
            <span>更换角色</span>
          </button>
        </div>

        <button 
          class="action-btn tertiary"
          @click="goToMenu"
          :disabled="isLoading"
        >
          <i class="icon-home"></i>
          <span>返回主菜单</span>
        </button>
      </div>

      <!-- 加载指示器 -->
      <div v-if="isLoading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">{{ loadingText }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'

/**
 * 游戏结束界面组件
 * 显示游戏结果、统计信息、成就和操作选项
 * @component
 * @example
 * <GameOverScreen 
 *   :final-score="5000"
 *   :distance="1200"
 *   :play-time="180"
 *   :is-victory="false"
 *   :is-new-high-score="true"
 *   @play-again="handlePlayAgain"
 *   @go-to-menu="handleGoToMenu"
 * />
 */

interface Achievement {
  id: string
  name: string
  description: string
  icon: string
  rarity: 'common' | 'rare' | 'epic' | 'legendary'
  reward: number
}

interface ScoreRecord {
  score: number
  distance: number
  date: Date
  isCurrent?: boolean
}

interface Props {
  /** 最终分数 */
  finalScore?: number
  /** 跑步距离 */
  distance?: number
  /** 游戏时间（秒） */
  playTime?: number
  /** 收集的金币数 */
  coinsCollected?: number
  /** 是否胜利 */
  isVictory?: boolean
  /** 是否创造新的最高分记录 */
  isNewHighScore?: boolean
  /** 是否创造新的距离记录 */
  isNewDistanceRecord?: boolean
  /** 跳跃次数 */
  jumpCount?: number
  /** 滑铲次数 */
  slideCount?: number
  /** 收集的道具数量 */
  powerUpsCollected?: number
  /** 完美跳跃次数 */
  perfectJumps?: number
  /** 最大连击数 */
  maxCombo?: number
  /** 角色名称 */
  characterName?: string
  /** 角色头像 */
  characterAvatar?: string
  /** 角色等级 */
  characterLevel?: number
  /** 当前经验值 */
  currentExp?: number
  /** 下一级所需经验值 */
  nextLevelExp?: number
  /** 新解锁的成就 */
  newAchievements?: Achievement[]
  /** 排行榜记录 */
  topScores?: ScoreRecord[]
  /** 是否显示排行榜 */
  showLeaderboard?: boolean
}

interface Emits {
  /** 再玩一次 */
  (e: 'play-again'): void
  /** 返回主菜单 */
  (e: 'go-to-menu'): void
  /** 分享成绩 */
  (e: 'share-score'): void
  /** 查看统计 */
  (e: 'view-stats'): void
  /** 更换角色 */
  (e: 'change-character'): void
}

const props = withDefaults(defineProps<Props>(), {
  finalScore: 0,
  distance: 0,
  playTime: 0,
  coinsCollected: 0,
  isVictory: false,
  isNewHighScore: false,
  isNewDistanceRecord: false,
  jumpCount: 0,
  slideCount: 0,
  powerUpsCollected: 0,
  perfectJumps: 0,
  maxCombo: 0,
  characterName: '默认角色',
  characterAvatar: '/default-character.png',
  characterLevel: 1,
  currentExp: 0,
  nextLevelExp: 100,
  newAchievements: () => [],
  topScores: () => [],
  showLeaderboard: true
})

const emit = defineEmits<Emits>()

// 响应式数据
const isLoading = ref(false)
const loadingText = ref('')

// 计算属性
const formattedFinalScore = computed(() => {
  return props.finalScore.toLocaleString()
})

const formattedDistance = computed(() => {
  return Math.floor(props.distance).toLocaleString()
})

const formattedPlayTime = computed(() => {
  const minutes = Math.floor(props.playTime / 60)
  const seconds = Math.floor(props.playTime % 60)
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
})

const experiencePercentage = computed(() => {
  if (props.nextLevelExp <= 0) return 100
  return Math.min(100, (props.currentExp / props.nextLevelExp) * 100)
})

/**
 * 格式化日期
 * @param date - 日期对象
 * @returns 格式化的日期字符串
 */
const formatDate = (date: Date): string => {
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString()
  }
}

/**
 * 再玩一次
 */
const playAgain = (): void => {
  if (isLoading.value) return
  
  isLoading.value = true
  loadingText.value = '准备新游戏...'
  
  setTimeout(() => {
    emit('play-again')
    isLoading.value = false
  }, 1000)
}

/**
 * 返回主菜单
 */
const goToMenu = (): void => {
  if (isLoading.value) return
  
  isLoading.value = true
  loadingText.value = '返回主菜单...'
  
  setTimeout(() => {
    emit('go-to-menu')
    isLoading.value = false
  }, 500)
}

/**
 * 分享成绩
 */
const shareScore = (): void => {
  if (isLoading.value) return
  
  const shareText = `我在跑酷游戏中获得了 ${formattedFinalScore.value} 分，跑了 ${formattedDistance.value} 米！你能超越我吗？`
  
  if (navigator.share) {
    navigator.share({
      title: '跑酷游戏成绩',
      text: shareText,
      url: window.location.href
    }).catch(console.error)
  } else {
    // 复制到剪贴板
    navigator.clipboard.writeText(shareText).then(() => {
      alert('成绩已复制到剪贴板！')
    }).catch(() => {
      alert('分享功能暂不可用')
    })
  }
  
  emit('share-score')
}

/**
 * 查看统计
 */
const viewStats = (): void => {
  if (isLoading.value) return
  emit('view-stats')
}

/**
 * 更换角色
 */
const changeCharacter = (): void => {
  if (isLoading.value) return
  emit('change-character')
}

// 生命周期钩子
onMounted(() => {
  // 播放结果音效
  if (props.isVictory) {
    console.log('播放胜利音效')
  } else {
    console.log('播放失败音效')
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/responsive.scss';

.game-over-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(12px);
  padding: 1rem;
  
  @include mobile-all {
    padding: 0.5rem;
  }

  .game-over-screen {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: $border-radius-xl;
    padding: 2rem;
    max-width: 650px;
    width: 100%;
    max-height: 95vh;
    overflow-y: auto;
    position: relative;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    animation: slideInUp 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    
    @include mobile-all {
      padding: 1.5rem;
      max-height: 98vh;
    }
    
    @include mobile-small {
      padding: 1rem;
    }

    &.victory {
      background: linear-gradient(135deg, #f0fff4 0%, #dcfce7 100%);
      border: 2px solid $success-color;
      box-shadow: 0 20px 60px rgba(34, 197, 94, 0.2);
    }

    .result-header {
      text-align: center;
      margin-bottom: $spacing-xl;

      .result-icon {
        width: 80px;
        height: 80px;
        background: $danger-color;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto $spacing-lg;
        animation: iconPulse 2s ease-in-out infinite;

        &.victory {
          background: $success-color;
        }

        i {
          font-size: 32px;
          color: white;
        }
      }

      .result-title {
        margin: 0 0 $spacing-sm 0;
        color: $text-color;
        font-size: 2rem;
        font-weight: bold;
      }

      .result-subtitle {
        margin: 0;
        color: $text-secondary;
        font-size: 1rem;
      }
    }

    .game-statistics {
      margin-bottom: $spacing-xl;

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: $spacing-md;
        margin-bottom: $spacing-lg;

        .stat-card {
          display: flex;
          align-items: center;
          gap: $spacing-sm;
          padding: $spacing-md;
          border-radius: $border-radius-md;
          position: relative;
          overflow: hidden;

          &.primary { background: linear-gradient(135deg, $primary-color, lighten($primary-color, 10%)); }
          &.secondary { background: linear-gradient(135deg, $secondary-color, lighten($secondary-color, 10%)); }
          &.accent { background: linear-gradient(135deg, $accent-color, lighten($accent-color, 10%)); }
          &.success { background: linear-gradient(135deg, $success-color, lighten($success-color, 10%)); }

          .stat-icon {
            width: 40px;
            height: 40px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;

            i {
              font-size: 18px;
              color: white;
            }
          }

          .stat-content {
            flex: 1;
            color: white;

            .stat-value {
              font-size: 1.5rem;
              font-weight: bold;
              font-family: 'Courier New', monospace;
              line-height: 1;
            }

            .stat-label {
              font-size: 0.75rem;
              opacity: 0.9;
              margin-top: 2px;
            }

            .stat-badge {
              position: absolute;
              top: -4px;
              right: -4px;
              background: $warning-color;
              color: white;
              font-size: 0.625rem;
              padding: 2px 6px;
              border-radius: $border-radius-sm;
              font-weight: bold;
              animation: badgeBounce 1s ease-in-out infinite;
            }
          }
        }
      }

      .detailed-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: $spacing-lg;

        .stats-section {
          background: $bg-secondary;
          padding: $spacing-md;
          border-radius: $border-radius-md;

          h4 {
            margin: 0 0 $spacing-md 0;
            color: $primary-color;
            font-size: 1rem;
          }

          .stats-list {
            display: flex;
            flex-direction: column;
            gap: $spacing-xs;

            .stats-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: $spacing-xs 0;
              border-bottom: 1px solid rgba(0, 0, 0, 0.05);

              &:last-child {
                border-bottom: none;
              }

              .stats-name {
                font-size: 0.875rem;
                color: $text-secondary;
              }

              .stats-value {
                font-weight: bold;
                color: $text-color;
                font-family: 'Courier New', monospace;
              }
            }
          }

          .character-info {
            display: flex;
            align-items: center;
            gap: $spacing-md;

            .character-avatar {
              width: 60px;
              height: 60px;
              border-radius: 50%;
              overflow: hidden;
              flex-shrink: 0;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }

            .character-details {
              flex: 1;

              .character-name {
                font-weight: bold;
                color: $text-color;
                margin-bottom: 2px;
              }

              .character-level {
                font-size: 0.875rem;
                color: $text-secondary;
                margin-bottom: $spacing-xs;
              }

              .experience-bar {
                width: 100%;
                height: 6px;
                background: rgba(0, 0, 0, 0.1);
                border-radius: 3px;
                overflow: hidden;
                margin-bottom: 2px;

                .exp-fill {
                  height: 100%;
                  background: $primary-color;
                  transition: width 0.5s ease;
                }
              }

              .exp-text {
                font-size: 0.75rem;
                color: $text-secondary;
              }
            }
          }
        }
      }
    }

    .achievements-section {
      margin-bottom: $spacing-xl;
      text-align: center;

      h3 {
        margin: 0 0 $spacing-lg 0;
        color: $accent-color;
        font-size: 1.25rem;
      }

      .achievements-list {
        display: flex;
        flex-direction: column;
        gap: $spacing-sm;

        .achievement-item {
          display: flex;
          align-items: center;
          gap: $spacing-md;
          padding: $spacing-md;
          border-radius: $border-radius-md;
          background: $bg-secondary;
          animation: achievementSlideIn 0.5s ease-out;

          &.rare { border-left: 4px solid $secondary-color; }
          &.epic { border-left: 4px solid $accent-color; }
          &.legendary { border-left: 4px solid $warning-color; }

          .achievement-icon {
            width: 48px;
            height: 48px;
            background: $primary-color;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;

            i {
              font-size: 20px;
              color: white;
            }
          }

          .achievement-info {
            flex: 1;
            text-align: left;

            .achievement-name {
              font-weight: bold;
              color: $text-color;
              margin-bottom: 2px;
            }

            .achievement-description {
              font-size: 0.875rem;
              color: $text-secondary;
              margin-bottom: 4px;
            }

            .achievement-reward {
              font-size: 0.75rem;
              color: $accent-color;
              font-weight: bold;
            }
          }
        }
      }
    }

    .leaderboard-preview {
      margin-bottom: $spacing-xl;

      h3 {
        margin: 0 0 $spacing-md 0;
        color: $text-color;
        text-align: center;
      }

      .leaderboard-list {
        background: $bg-secondary;
        border-radius: $border-radius-md;
        overflow: hidden;

        .leaderboard-item {
          display: grid;
          grid-template-columns: 40px 1fr 80px 80px;
          gap: $spacing-sm;
          align-items: center;
          padding: $spacing-sm $spacing-md;
          border-bottom: 1px solid rgba(0, 0, 0, 0.05);

          &:last-child {
            border-bottom: none;
          }

          &.current {
            background: rgba($primary-color, 0.1);
            font-weight: bold;
          }

          .rank {
            font-weight: bold;
            color: $primary-color;
            text-align: center;
          }

          .score {
            font-family: 'Courier New', monospace;
            color: $text-color;
          }

          .distance {
            font-size: 0.875rem;
            color: $text-secondary;
            text-align: right;
          }

          .date {
            font-size: 0.75rem;
            color: $text-light;
            text-align: right;
          }
        }
      }
    }

    .action-buttons {
      display: flex;
      flex-direction: column;
      gap: $spacing-md;
      align-items: center;

      .action-btn {
        display: flex;
        align-items: center;
        gap: $spacing-sm;
        padding: $spacing-md $spacing-lg;
        border: none;
        border-radius: $border-radius-md;
        font-size: 1rem;
        cursor: pointer;
        transition: $transition-normal;
        text-decoration: none;

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        i {
          font-size: 1.25rem;
        }

        &.large {
          padding: $spacing-lg $spacing-xl;
          font-size: 1.125rem;
          font-weight: bold;
        }

        &.primary {
          background: $primary-color;
          color: white;

          &:hover:not(:disabled) {
            background: darken($primary-color, 10%);
            transform: translateY(-2px);
          }
        }

        &.secondary {
          background: $bg-secondary;
          color: $text-color;

          &:hover:not(:disabled) {
            background: darken($bg-secondary, 5%);
            transform: translateY(-2px);
          }
        }

        &.tertiary {
          background: transparent;
          color: $text-secondary;
          border: 1px solid $text-light;

          &:hover:not(:disabled) {
            background: $bg-secondary;
            color: $text-color;
          }
        }
      }

      .secondary-buttons {
        display: flex;
        gap: $spacing-sm;
        flex-wrap: wrap;
        justify-content: center;
      }
    }

    .loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(255, 255, 255, 0.9);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border-radius: $border-radius-xl;

      .loading-spinner {
        width: 50px;
        height: 50px;
        border: 4px solid $bg-secondary;
        border-top: 4px solid $primary-color;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: $spacing-md;
      }

      .loading-text {
        color: $text-secondary;
        font-size: 1rem;
      }
    }
  }
}

// 动画定义
@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes iconPulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes badgeBounce {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
}

@keyframes achievementSlideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 图标样式
.icon-trophy::before { content: '🏆'; }
.icon-skull::before { content: '💀'; }
.icon-star::before { content: '⭐'; }
.icon-distance::before { content: '📏'; }
.icon-time::before { content: '⏱️'; }
.icon-coin::before { content: '🪙'; }
.icon-restart::before { content: '🔄'; }
.icon-share::before { content: '📤'; }
.icon-chart::before { content: '📊'; }
.icon-character::before { content: '👤'; }
.icon-home::before { content: '🏠'; }

// 响应式设计
@media (max-width: $breakpoint-md) {
  .game-over-overlay .game-over-screen {
    padding: $spacing-lg;
    max-width: 500px;

    .game-statistics {
      .stats-grid {
        grid-template-columns: 1fr 1fr;
        gap: $spacing-sm;
      }

      .detailed-stats {
        grid-template-columns: 1fr;
      }
    }

    .action-buttons .secondary-buttons {
      flex-direction: column;
      width: 100%;

      .action-btn {
        width: 100%;
        justify-content: center;
      }
    }
  }
}

@media (max-width: $breakpoint-sm) {
  .game-over-overlay .game-over-screen {
    .game-statistics .stats-grid {
      grid-template-columns: 1fr;
    }

    .leaderboard-preview .leaderboard-list .leaderboard-item {
      grid-template-columns: 30px 1fr 60px;
      
      .date {
        display: none;
      }
    }
  }
}
</style>